package com.googlecode.jerato.library;

import java.util.HashMap;

import com.googlecode.jerato.core.Function;

public class FunctionService {

	protected HashMap _cache = new HashMap();

	public class FunctionDefine{
		public String _name;
		public Class _clazz;
		public Function _instance;
	}

	public boolean exists(String name){
		synchronized (_cache) {
			return _cache.containsKey(name);
		}
	}

	public Function get(String functionName){
		if(functionName == null){
			throw new IllegalArgumentException("Name is null.");
		}
		synchronized (_cache) {
			if(_cache.containsKey(functionName)){
				FunctionDefine funcDec = (FunctionDefine)_cache.get(functionName);
				return funcDec._instance;
			}
			Class clazz = null;
			try{
				clazz = Class.forName(functionName);
			}
			catch(ClassNotFoundException ce){
				throw new SystemException("function not found. name=" + functionName, ce);
			}
			Function func;
			try {
				func = (Function)clazz.newInstance();
			} catch (InstantiationException e) {
				throw new SystemException("function not found. name=" + functionName, e);
			} catch (IllegalAccessException e) {
				throw new SystemException("function not found. name=" + functionName, e);
			}
			FunctionDefine funcDec = new FunctionDefine();
			funcDec._name = functionName;
			funcDec._clazz = clazz;
			funcDec._instance = func;
			_cache.put(functionName, funcDec);
			return func;
		}
	}
}
